package com.smarthealthring.mm.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.clj.fastble.BleManager;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jakewharton.rxbinding2.view.RxView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.smarthealthring.mm.R;
import com.smarthealthring.mm.api.ApiRequest;
import com.smarthealthring.mm.base.BaseFragment;
import com.smarthealthring.mm.bean.SyncDataRes;
import com.smarthealthring.mm.ble.BdProtocol;
import com.smarthealthring.mm.ble.RtEvent;
import com.smarthealthring.mm.ble.SyncDataBean;
import com.smarthealthring.mm.ble.SyncDataEvent;
import com.smarthealthring.mm.contract.HealthyContract;
import com.smarthealthring.mm.event.WechatLoginEvent;
import com.smarthealthring.mm.presenter.HealthyPresenter;
import com.smarthealthring.mm.ui.activity.DeviceInfoActivity;
import com.smarthealthring.mm.ui.activity.DevicesActivity;
import com.smarthealthring.mm.ui.activity.HomeActivity;
import com.smarthealthring.mm.ui.activity.HrDetailActivity;
import com.smarthealthring.mm.ui.activity.SleepDetailActivity;
import com.smarthealthring.mm.ui.activity.StepDetailActivity;
import com.smarthealthring.mm.utils.BitmapUtils;
import com.smarthealthring.mm.utils.ErrorHanding;
import com.smarthealthring.mm.utils.OnekeyShare2;
import com.smarthealthring.mm.utils.RandomUtil;
import com.smarthealthring.mm.utils.RxBus;
import com.smarthealthring.mm.utils.RxBusBaseMessage;
import com.smarthealthring.mm.utils.SPUtils;
import com.smarthealthring.mm.utils.TimeUtils;
import com.smarthealthring.mm.utils.ToastUtil;
import com.smarthealthring.mm.utils.statusbar.StatusBarCompat;
import com.smarthealthring.mm.widgets.MyRefreshLayout;
import com.smarthealthring.mm.widgets.RingHeader;
import com.smarthealthring.mm.widgets.RingProgressBar;
import com.smarthealthring.mm.widgets.SingleItemView;

import java.util.HashMap;

import butterknife.BindView;
import cn.sharesdk.onekeyshare.OnekeyShare;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;

/**
 * Created by hewei26 on 2018/4/8.
 */

public class HealthyFragment extends BaseFragment<HealthyPresenter> implements HealthyContract.View {

    @BindView(R.id.ringpb)
    RingProgressBar mRingProgressBar;
    @BindView(R.id.siv_connect)
    SingleItemView sivConnect;
    @BindView(R.id.siv_power)
    SingleItemView sivPower;
    @BindView(R.id.siv_heart_rate)
    SingleItemView sivHeartRate;
    @BindView(R.id.siv_sleep)
    SingleItemView sivSleep;
    @BindView(R.id.siv_weight)
    SingleItemView sivWeight;
    @BindView(R.id.tv_current_step)
    TextView mTvCurrentStep;
    @BindView(R.id.tv_kaluli)
    TextView mTvaluli;
    @BindView(R.id.tv_km)
    TextView mTvKm;
    @BindView(R.id.tv_steps)
    TextView mTvSteps;
    @BindView(R.id.tv_km_kaluli)
    TextView mTvKmKaluli;
    @BindView(R.id.smart_refresh)
    MyRefreshLayout refreshLayout;
    @BindView(R.id.rl_progress)
    RelativeLayout mRlProgress;
    @BindView(R.id.btn_share)
    ImageView mBtnShare;
    @BindView(R.id.ll_healthy_layout)
    LinearLayout mHealthLayout;

    int REFRESH_STATE = -1;
    private float downY;
    private String walkvalue;

    @Override
    protected int getLayoutId() {
        return R.layout.frag_healthy;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initEventAndData() {
        StatusBarCompat.setStatusBarColor(mActivity, ContextCompat.getColor(mActivity, R.color.title_blue));
        //已完成步数
        mRingProgressBar.setProgress(50);

        //检查设备是否连接
        if (SPUtils.getInt(SPUtils.BOND_STATE, 0) == 1) {
            sivConnect.setVisibility(View.GONE);
        } else {
            sivConnect.setVisibility(View.VISIBLE);
        }

        RxView.clicks(sivConnect)
                .subscribe(o ->
                        startActivity(new Intent(mContext, DevicesActivity.class))
                );

        registerEvent();

        refreshLayout.setRefreshHeader(new RingHeader(mContext));
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {

                Log.e("onRefresh===", REFRESH_STATE + "--" + SPUtils.getInt(SPUtils.BOND_STATE, 0) + "--"
                        + BleManager.getInstance().isConnected(SPUtils.getString(SPUtils.DEVICE_MAC, "")));

                if (SPUtils.getInt(SPUtils.BOND_STATE, 0) == 1) {
                    if (REFRESH_STATE == 1) {   // 同步数据
                        if (BleManager.getInstance().isConnected(SPUtils.getString(SPUtils.DEVICE_MAC, ""))) {
                            if(BdProtocol.IS_SYNC_DATA==0){
                                BdProtocol.syncData(BdProtocol.mBleDevice);
                            }
                        } else {
                            ToastUtil.longShow("设备未连接");
                            refreshlayout.finishRefresh(500);
                        }
                    } else {    // 连接设备
                        BdProtocol.connectWithMac(SPUtils.getString(SPUtils.DEVICE_MAC, ""));
                    }
                } else {    // 未绑定
                    ToastUtil.longShow("设备未绑定");
                    refreshlayout.finishRefresh(500);
                }


            }
        });

//        refreshLayout.autoRefresh();  这个是进入页面自动刷新

        // 默认数据
        String s_syncDataCache = SPUtils.getString(SPUtils.SYNC_DATA_BEAN, "no_data");
        if (!"no_data".equals(s_syncDataCache)) {
            Gson gson = new Gson();
            SyncDataRes syncDataRes = gson.fromJson(s_syncDataCache, SyncDataRes.class);
            setHomeData(syncDataRes);
        }

        Log.e("life_healthy_fra===", "onInit...");

        sivPower.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext, DeviceInfoActivity.class));
            }
        });

        mRlProgress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext, StepDetailActivity.class));
            }
        });

        mBtnShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Bitmap bmp = BitmapUtils.getSnapBitmap(mHealthLayout);
//                Bitmap bitmap = captureScreenWindow();
//                showShare(true, null, bitmap);
                refreshLayout.autoRefresh();
            }
        });

        sivHeartRate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext, HrDetailActivity.class));
            }
        });
        sivSleep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext, SleepDetailActivity.class));
            }
        });

        mRlProgress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext, StepDetailActivity.class));
            }
        });
    }

    @Override
    protected HealthyPresenter createPresenter() {
        return new HealthyPresenter();
    }

    @Override
    protected boolean isLazyLoad() {
        return false;
    }

    public static HealthyFragment getInstance() {
        return new HealthyFragment();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.e("life_healthy_fra===", "onHidden...");
        if (!hidden) {
            StatusBarCompat.setStatusBarColor(mActivity, ContextCompat.getColor(mActivity, R.color.title_blue));
        }
        //检查设备是否绑定
        if (SPUtils.getInt(SPUtils.BOND_STATE, 0) == 1) {
            sivConnect.setVisibility(View.GONE);
        } else {
            sivConnect.setVisibility(View.VISIBLE);
            return;
        }

//        if (BleManager.getInstance().isConnected(SPUtils.getString(SPUtils.DEVICE_MAC, "")) &&
//                SPUtils.getInt(SPUtils.IS_FIRST_BOND, 1) == 1) {
//            refreshLayout.autoRefresh();
//            Log.e("是首次绑定===", "刷新同步数据...");
//            SPUtils.setInt(SPUtils.IS_FIRST_BOND, 0);
//        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //检查设备是否连接
        if (SPUtils.getInt(SPUtils.BOND_STATE, 0) == 1) {
            sivConnect.setVisibility(View.GONE);
        } else {
            sivConnect.setVisibility(View.VISIBLE);
            return;
        }
        Log.e("life_healthy_fra===", "onResume...");

        if (SPUtils.getInt(SPUtils.BOND_STATE, 0) == 0)
            return;
        if (!BleManager.getInstance().isConnected(SPUtils.getString(SPUtils.DEVICE_MAC, ""))) {
            Log.e("调用连接设备的刷新===", "in...");
            REFRESH_STATE = 0;
            refreshLayout.autoRefresh();
            RingHeader refreshHeader = (RingHeader) refreshLayout.getRefreshHeader();
            refreshHeader.setTextRefreshText("正在连接设备和同步数据");
        }

        // 如果是（首次）绑定调用下拉刷新
        if (BleManager.getInstance().isConnected(SPUtils.getString(SPUtils.DEVICE_MAC, "")) &&
                SPUtils.getInt(SPUtils.IS_FIRST_BOND, 1) == 1) {
            Log.e("是首次绑定===", "刷新同步数据...");
            REFRESH_STATE = 1;
            refreshLayout.autoRefresh();
            SPUtils.setInt(SPUtils.IS_FIRST_BOND, 0);
        }

        // 体重和目标步数
        sivWeight.setmTvRight(SPUtils.getInt(SPUtils.WEIGHT_TARGET, 65) + "kg");
        sivWeight.setmTvSubTitle(TimeUtils.getCurTimeString());
        // 路程百分比
        int spSport = SPUtils.getInt(SPUtils.SPORT_TARGET, 8);
        mTvKmKaluli.setText("目标步数：" + spSport * 1000);
        int pro = (Integer.parseInt(walkvalue));
        mRingProgressBar.setProgress(pro * 100 / (spSport * 1000));

    }

    void registerEvent() {

        RxBus.getInstance().tObservable(SyncDataEvent.SYNC_DATA, SyncDataBean.class)
                .subscribe(new Consumer<SyncDataBean>() {
                    @Override
                    public void accept(SyncDataBean syncDataBean) throws Exception {
                        Log.e("请求同步数据到服务器===", "in...");
                        mPresenter.syncData(new HashMap<String, String>() {{
                            put("trans_id", "2011");
                            put("sign", "1111");
                            put("deviceid", SPUtils.getString(SPUtils.DEVICE_MAC, ""));
                            put("username", SPUtils.getString(SPUtils.USERNAME, ""));
                            put("nonce_str", RandomUtil.getRandomString(32));
                            put("token", SPUtils.getString(SPUtils.TOKEN, "token=="));
                            Gson gson = new Gson();
                            String s_SyncDatabean = gson.toJson(syncDataBean);
                            put("data", s_SyncDatabean);
                            Log.e("syncDatabean===", s_SyncDatabean);
                        }});
                    }
                });

        RxBus.getInstance().tObservable(RtEvent.CONNECT_SUCCESS, RxBusBaseMessage.class)
                .subscribe(new Consumer<RxBusBaseMessage>() {
                    @Override
                    public void accept(RxBusBaseMessage rxBusBaseMessage) throws Exception {
                        Log.e("register===", "连接成功...");
//                        refreshLayout.finishRefresh();

                        REFRESH_STATE = 1;
                        RingHeader refreshHeader = (RingHeader) refreshLayout.getRefreshHeader();
                        refreshHeader.setTextRefreshText("正在同步数据");

//                        try {
//                            Thread.sleep(2000);
//                        } catch (InterruptedException e) {
//                            e.printStackTrace();
//                        }
//
//                        refreshLayout.autoRefresh();
                        if (BleManager.getInstance().isConnected(SPUtils.getString(SPUtils.DEVICE_MAC, ""))) {
                            if(BdProtocol.IS_SYNC_DATA==0){
                                BdProtocol.syncData(BdProtocol.mBleDevice);
                            }
                        }
                    }
                });
    }

    @Override
    public void syncDataSuccess(SyncDataRes syncDataRes) {
        // 保存到Sp
        Gson gson = new Gson();
        SPUtils.setString(SPUtils.SYNC_DATA_BEAN, gson.toJson(syncDataRes));

        setHomeData(syncDataRes);

        refreshLayout.finishRefresh(500);

        BdProtocol.IS_SYNC_DATA = 0;    // 同步数据状态置为0

    }

    @Override
    public void syncDataFail() {
        refreshLayout.finishRefresh(500);
    }

    private void setHomeData(SyncDataRes syncDataRes) {
        // 设置时间
        sivPower.setmTvSubTitle(TimeUtils.getCurTimeString());
        sivHeartRate.setmTvSubTitle(TimeUtils.getCurTimeString());
        sivSleep.setmTvSubTitle(TimeUtils.getCurTimeString());

        sivPower.setmTvRight(SPUtils.getInt(SPUtils.DEVICE_POWER, 75) + "%");
        if ("1".equals(syncDataRes.getHr().getHasvalue())) {
            sivHeartRate.setmTvRight(syncDataRes.getHr().getXinlvvalue() + "次/分");
            SPUtils.setString(SPUtils.LAST_HR, syncDataRes.getHr().getXinlvvalue());
        }else {
            sivHeartRate.setmTvRight(SPUtils.getString(SPUtils.LAST_HR,"85") + "次/分");
        }
        if ("1".equals(syncDataRes.getSleep().getHasvalue())) {
            sivSleep.setmTvRight(syncDataRes.getSleep().getAlltime());

        }
        if ("1".equals(syncDataRes.getWalk().getHasvalue())) {
            mTvCurrentStep.setText(syncDataRes.getWalk().getWalkvalue());
            mTvKmKaluli.setText("目标步数：" + SPUtils.getInt(SPUtils.SPORT_TARGET, 10) * 1000);
            mTvaluli.setText(syncDataRes.getWalk().getKaluli() + "千卡");
            mTvKm.setText(syncDataRes.getWalk().getWalkkm() + "Km");
            walkvalue = syncDataRes.getWalk().getWalkvalue();
            mTvSteps.setText(walkvalue);
        }

        // 路程百分比
        int spSport = SPUtils.getInt(SPUtils.SPORT_TARGET, 8);
        int pro = (Integer.parseInt(syncDataRes.getWalk().getWalkvalue()) * 100 / (spSport * 1000));
        mRingProgressBar.setProgress(pro);

    }

    //分享必须要写的方法
    private void showShare(boolean silent, String platform, Bitmap bmp) {
        OnekeyShare2 oks = new OnekeyShare2();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        oks.setBitmapToShare(bmp);
        oks.setSite(mActivity.getString(R.string.app_name));
        oks.setSilent(silent);
        // 启动分享GUI
        try {
            oks.show(mActivity);
        } catch (Exception e) {
            ToastUtil.longShow("分享失败");
        }
    }

    /**
     * 截取全屏
     *
     * @return
     */
    public Bitmap captureScreenWindow() {
        getActivity().getWindow().getDecorView().setDrawingCacheEnabled(true);
        Bitmap bmp = getActivity().getWindow().getDecorView().getDrawingCache();
        return bmp;
    }

}
